﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfControlDemo.依赖属性;

namespace WpfControlDemo.数据绑定
{
    /// <summary>
    /// DataBindingWindow1.xaml 的交互逻辑
    /// </summary>
    public partial class DataBindingWindow1 : Window
    {
        public DataBindingWindow1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 代码通过中间对象设置控件绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 通过中间对象将两个控件的绑定关联起来
            UserInfo userInfo = new UserInfo(); // 中间对象
            userInfo.UserId = 101;

            Binding bind2 = new Binding("Text");  // 绑定属性
            bind2.Source = txtName5;// 源对象
            bind2.Mode = BindingMode.OneWay;//绑定模式
            //设置绑定  参数1：目标对象 参数2：依赖属性 参数3：绑定源
            BindingOperations.SetBinding(userInfo, UserInfo.UserNameProperty, bind2);

            //userInfo作为源，UserName
            Binding bind3 = new Binding("UserName");
            bind3.Source = userInfo;//源对象
            bind3.Mode = BindingMode.OneWay;//绑定模式
            //设置绑定  参数1：目标对象 参数2：依赖属性 参数3：绑定源
            BindingOperations.SetBinding(lblName, Label.ContentProperty, bind3);

        }

        /// <summary>
        /// 代码设置控件间的绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            //代码设置控件间的绑定
            Binding bind1 = new Binding("Text"); // 绑定的属性
            bind1.Source = txtName3;//源对象
            bind1.Mode = BindingMode.OneWay;//绑定模式
            //目标对象 - 设置绑定 参数1：绑定的依赖属性  参数2：源
            txtName5.SetBinding(TextBox.TextProperty, bind1); 
            //BindingOperations.SetBinding(txtName5, TextBox.TextProperty, bind1);
        }
    }
}
